package com.stephenweng.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stephenweng.common.lang.Result;
import com.stephenweng.entity.Blog;
import com.stephenweng.entity.User;
import com.stephenweng.mapper.BlogMapper;
import com.stephenweng.service.IBlogService;
import com.stephenweng.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-05-24
 */
@RestController
public class BlogController {
    @Autowired
    IBlogService blogService;
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
        Page page = new Page(currentPage, 5);
//        System.out.println(userId);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().eq("user_id",1).orderByDesc("created"));
        return Result.succ(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已删除！");
        return Result.succ(blog);

}

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {
        System.out.println(blog.toString());
        Blog temp = null; //一个空对象用于赋值
        //如果有id则是编辑 没有则新建添加blog内容
        if(blog.getId() != null) {
            //将数据库的内容传递给temp
            temp = blogService.getById(blog.getId());
            //只能编辑自己的文章
            Assert.isTrue(temp.getUserId() == ShiroUtil.getProfile().getId(), "没有权限编辑");
        } else {
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        //将blog的值赋给temp 忽略 id userid created status 引用于hutool
        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
        blogService.saveOrUpdate(temp);
        return Result.succ("操作成功", null);
    }

    @RequiresAuthentication  //需要认证之后才能操作
    @PostMapping("/blogdel/{id}")
    public Result del(@PathVariable Long id){
        boolean b = blogService.removeById(id);
        //判断是否为空 为空则断言异常
        if(b==true){

            return Result.succ("文章删除成功");
        }else{
            return Result.fail("文章删除失败");
        }
    }

     //需要认证之后才能操作
    @GetMapping("/sort")
    public Result sort(){
      QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
      //获取数据库中的blog_sort 存进字符串数组SortNum中
      queryWrapper.orderByDesc("tag");//这个是按某一列排序、升序还是降序来着有点忘了
        List<Blog> blog = blogService.list(queryWrapper);
//        String[] SortNum = new String[100];
//        for (int i =0 ;i<blog.size() ; i++){
//            Blog blog1 = blog.get(i);
//            SortNum[i] = blog1.getBlogSort();
//        }
        List<JSONObject> res=new ArrayList<>();
        int i=0;
        String cur = blog.get(0).getTag();
        int blogNum=0;
        while (i<blog.size()){
            Blog temp = blog.get(i);
            if (temp.getTag().equals(cur)) blogNum++;
            else {
                res.add(new JSONObject()
                        .putOnce("tagName",cur)
                        .putOnce("Num",blogNum));
                blogNum=1;
                cur=temp.getTag();
            }
            i++;
        }
        res.add(new JSONObject()
                .putOnce("tagName",cur)
                .putOnce("Num",blogNum));

        //统计blog_sort中各个类型出现的数量
//        Map<Object,Object> tapName = new HashMap<>();
//        Map<Object,Object> tapNum = new HashMap<>();
//        Map<Object,Object> tapSort = new HashMap<>();
//         Map map = new HashMap<>();
//        for (String str : SortNum){
//            Integer num = (Integer) map.get(str);
//            map.put(str,num==null ? 1 : num+1);
//        }
//        Set set = map.entrySet();
//        Iterator it = set.iterator();
//        while (it.hasNext()){
//            Map.Entry entry = (Map.Entry) it.next();
//            System.out.println("类型 " + entry.getKey() + " 出现次数 : " + entry.getValue());
//          if (entry.getKey()!=null){
//              tapName.put("tapName",entry.getValue());
//              tapNum.put("tapnum",entry.getValue());
//              tapSort.put()
//          }
//        }


        return Result.succ(res);
    }

    //通过tag来获取博客信息
//    @GetMapping("/selectByTag/{tagName}")
//        public Result listbyTag(  @RequestParam(defaultValue = "1") Integer currentPage, @PathVariable String tagName){
//        Page page = new Page(currentPage, 5);
//        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().eq("tag",tagName).orderByDesc("created"));
//        return Result.succ(pageData);
//    }

    //通过tag来获取博客信息
    @GetMapping("/selectByTag")
    public Result listbyTag(  @RequestParam(defaultValue = "1") Integer currentPage, @RequestParam String tagName){
        Page page = new Page(currentPage, 5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().eq("tag",tagName).orderByDesc("created"));
        return Result.succ(pageData);
    }

}
